﻿/*
file js quản lý người dùng
*/
$(document).ready(function () {
    if (typeof (VOFFICE) == "undefined") {
        VOFFICE = {};
    }

    VOFFICE.ManageObject = (function () {
        var methods = {};

        methods.ObjectForm = null;
        methods.Node = 0;
        methods.ParentId = 0;
        methods.Collection = null;
        methods.CustomValidate = {
            errorLabelContainer: "#menu-form-error",
            rules: {
                Name: { required: true }
            },
            messages: {
                Name: { required: jsResources.lang.ManageUserUserNameRequired }
            }
        };
        methods.dialog = $('#dialog-box').dialog({
            autoOpen: false,
            show: "fade", //fix ie bug
            hide: "fade",
            modal: true,
            height: 'auto',
            width: 600,
            open: function (event, ui) {
                //$('.ui-dialog-titlebar', ui.dialog || ui).hide();
            },
            close: function (event, ui) {
            }
        });
        var $detailForm = $("#dept-detail");
        methods.busy = false;
        
        methods.buildJsTree = function () {
            $('#systemMenu').jstree({
                json_data: {
                    "ajax": {
                        "url": "/SystemMenu/get_system_menu/?nocache=" + (new Date()).toJSON(),
                        "type": "POST",
                        "dataType": "json",
                        "contentType": "application/json charset=utf-8"
                    }
                },
                crrm: {
                    move: {
                        "check_move": function (m) {
                            var p = this._get_parent(m.o);
                            if (!p)
                                return false;
                            if (m.cr === -1)
                                return false;
                            return true;
                        }

                    }
                },
                contextmenu: {
                    "items": function ($node) {
                        return {
                            "create": {
                                "label": "Thêm mới",
                                "icon": "../content/images/add_icon.png",
                                "action": function (obj) {
                                    if (!!obj) {
                                        methods.ParentId = obj.attr('id');
                                        var addView = new ObjectForm({ model: new SystemMenu() });
                                        addView.render();
                                    }
                                }
                            },
                            "update": {
                                "label": "Sửa",
                                "icon": "../content/images/file_edit.png",
                                "action": function (obj) {
                                    SaveIndicator.indicate($.get('/SystemMenu/get_menu', { 'id': obj.attr('id'), nocache: (new Date()).toJSON() }, function (data) {
                                        if (!!data && data.Status == true) {
                                            if (!!data.Result) {
                                                var systemMenu = new SystemMenu({
                                                    'id': data.Result.id,
                                                    'Name': data.Result.Name,
                                                    'IsActive': data.Result.IsActive,
                                                    'IsShow': data.Result.IsShow,
                                                    'Description': data.Result.Description
                                                });
                                                var editView = new ObjectForm({ model: systemMenu });
                                                editView.render();
                                            } else {

                                            }
                                        }
                                    }));
                                }
                            },
                            "delete": {
                                "label": "Xóa",
                                "icon": "../content/images/delete_icon.png",
                                "action": function (obj) {
                                    var $deleteConfirm = $("<div class='delete-confirm'/>");
                                    $deleteConfirm.append('<p>' + jsResources.lang.ManageSystemMenu_ConfirmMessage + obj.children("a").text() + '</p>');
                                    methods.dialog.html($deleteConfirm);
                                    methods.dialog.dialog('option', 'title', jsResources.lang.ManageSystemMenu_DialogDeleteTitle);
                                    var dialogCloseButtons = jsResources.lang.Delete;
                                    var dialogUpdateButtons = jsResources.lang.Update;
                                    var dialogButtons = {};
                                    dialogButtons[dialogUpdateButtons] = function () {
                                        SaveIndicator.indicate($.post('/SystemMenu/delete_menu', { 'curentid': obj.attr('id') }, function (data) {
                                            if (!!data && data.Status == true) {
                                                $(".delete-confirm").empty();
                                                $(".delete-configm").append('<p>' + jsResources.lang.ManageSystemMenu_ConfirmMessage + '</p>');
                                                setInterval(methods.closeDialog(), 1000);
                                            }else {
                                                $(".delete-confirm").empty();
                                                $(".delete-confirm").append('<p>' + data.Result + '</p>');
                                                //methods.closeDialog();
                                            }
                                        }));
                                    };
                                    dialogButtons[dialogCloseButtons] = function () { $(this).dialog('close'); };
                                    methods.dialog.dialog(
                                        {
                                            buttons: dialogButtons
                                        }
                                    );
                                    methods.dialog.dialog('open');
                                }
                            }
                        };
                    }
                },
                plugins: ["themes", "json_data", "ui", "dnd", "crrm", "contextmenu"]
            });
            $('#systemMenu').bind("loaded.jstree", function (event, data) {
                $('#systemMenu').jstree("open_all");
            });
            $("#systemMenu").bind("select_node.jstree", function (event, data) {
                var selectedObj = data.rslt.obj;
                methods.ParentId = selectedObj.attr('id');
            });
            $('#systemMenu').bind("move_node.jstree", function (e, data) {
                data.rslt.o.each(function (i) {
                    $.ajax({
                        async: false,
                        type: 'POST',
                        url: "/SystemMenu/move_menu",
                        data: {
                            "curentid": $(this).attr("id"),
                            "parentid": data.rslt.np.attr("id")
                        },
                        success: function (r) {
                            methods.buildJsTree();
                        }
                    });
                });
            });
            if (!!methods.ParentId) {
                $("#systemMenu").bind("reselect.jstree", function () {
                    $("#systemMenu").jstree("select_node", "#" + methods.ParentId);
                });
            }

        };
        /*
        Hiển thị dialog để thêm sổ mới
        */
        var addNew = function () {
            var addView = new ObjectForm({ model: new SystemMenu() });
            addView.render();
        };
        /*
        Hiển thị form để sửa một sổ đã tạo
        */
        methods.edit = function (model) {
            var editView = new ObjectForm({ model: model });
            editView.render();
        };
        /* Hien thi form detail */
        methods.detail = function (model) {
            methods.ObjectForm = new ObjectForm({ model: model });
            $detailForm.html(methods.ObjectForm.render().el);
            $('#dept-form').validate(methods.CustomValidateUpdate);
            $detailForm.fadeIn('slow');
        };

        /*
        Đóng dialog
        */
        methods.closeDialog = function () {
            methods.dialog.dialog('close');
        };

        /*
        gọi lại hàm validate form sau khi nó bị backbone render lại
        */
        methods.recallValidate = function () {
            $('#dept-form').validate(methods.CustomValidate);
        };

        // quy ước về hàm khởi tạo
        methods.init = function () {
            methods.buildJsTree();
            $("#systemMenu").bind("reselect.jstree", function () {
                $("#systemMenu").jstree('select_node', 'ul > li:first');
            });
            $('#add-new').live('click', addNew);
            $("input:button", '.layout-container').button();
        };
        return methods;
    })(VOFFICE.ManageObject);


    //gọi hàm khởi tạo
    VOFFICE.ManageObject.init();
});
/*
View để thêm mới hay chỉnh sửa book (sổ công văn)
*/
window.ObjectForm = Backbone.View.extend({
    initialize: function () {
        this.model.bind("change", this.render, this);
        this.model.bind("destroy", this.close, this);
    },
    render: function () {
        var self = this;
        this.template = _.template($('#menu-form-template').html());
        $(this.el).html(this.template({ model: this.model.toJSON() }));

        VOFFICE.ManageObject.dialog.html($(this.el).html(this.template({ model: this.model.toJSON() })));
        var isNew = this.model.get('id') == 0;
        if (!isNew) {
            VOFFICE.ManageObject.dialog.dialog('option', 'title', jsResources.lang.ManageSystemMenu_DialogUpdateTitle);
        } else {
            VOFFICE.ManageObject.dialog.dialog('option', 'title', jsResources.lang.ManageSystemMenu_DialogAddTitle);
        }

        var dialogCloseButtons = jsResources.lang.ButtonClose;
        var dialogUpdateButtons = jsResources.lang.Update;
        var dialogButtons = {};
        dialogButtons[dialogUpdateButtons] = function () {
            //tao moi hay cap nhap du lieu
            SaveIndicator.indicate(self.model.save({
                'Name': $('#Name').val(),
                'Description': $('#Description').val(),
                'IsActive': $('#IsActive').is(':checked'),
                'IsShow': $('#IsShow').is(':checked'),
                'ParentId': VOFFICE.ManageObject.ParentId == 0 ? null : VOFFICE.ManageObject.ParentId
            }, {
                success: function (data) {
                    VOFFICE.ManageObject.closeDialog();
                },
                error: function (data) {
                    VOFFICE.ManageObject.closeDialog();
                },
                complete: function () {
                    VOFFICE.ManageObject.buildJsTree();
                    $("#systemMenu").bind("reselect.jstree", function () {
                        $("#systemMenu").jstree("select_node", "#" + VOFFICE.ManageObject.ParentId);
                    });
                }
            }));
        };
        dialogButtons[dialogCloseButtons] = function () { $(this).dialog('close'); };
        VOFFICE.ManageObject.dialog.dialog(
            {
                buttons: dialogButtons
            }
        );

        VOFFICE.ManageObject.dialog.dialog('open');

        return this;
    },

    close: function () {
        this.remove();
        this.unbind();
        this.model.unbind("change", this.render, this);
    }
});